package com.manager.controller;

import com.manager.entity.Member;
import com.manager.result.Result;
import com.manager.service.IMemberService;
import com.manager.vo.LoginVo;
import com.manager.vo.RegisterVo;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/member/")
public class MemberController {

    @javax.annotation.Resource
    private IMemberService memberService;


    @PostMapping("login")
    public Result<Object> login(@RequestBody LoginVo loginVo){
        Map<String, String> map = memberService.login(loginVo);

        if("1".equals(map.get("key"))){
            return Result.fail(Result.build(1, (String) map.get("message")));
        }
        return Result.ok(map);
    }


    @PostMapping("register")
    public Result<Object> register(@RequestBody RegisterVo registerVo){
        int res = memberService.register(registerVo);
        if(res <= 0){
            return Result.fail();
        }
        return Result.ok();
    }

    @GetMapping("info")
    public Result<List<String>> getInfo(@RequestParam("token") String token){

        Member member = memberService.getInfo(token);
        List<String> nameList = new ArrayList<>();
        nameList.add(member.getMemberName());
        return Result.ok(nameList);
    }

    @GetMapping("detail")
    public Result<Member> getDetail(@RequestParam("token") String token){

        Member member = memberService.getInfo(token);
        return Result.ok(member);
    }


    @PostMapping("/upload")
    public Result<String> uploadAvatar(MultipartFile file) {

        if (file.isEmpty()) {
            return Result.fail("上传的文件为空");
        }
        String fileName = memberService.upload(file);
        return Result.ok(fileName);
    }


    @GetMapping("avatar/{fileName}")
    public ResponseEntity<Resource> getAvatar(@PathVariable String fileName) {

        return memberService.getAvatar(fileName);
    }

    @PutMapping("update")
    public Result<String> update(@RequestBody Member member){
        int res = memberService.updateMember(member);
        if(res <= 0){
            return Result.fail("修改失败");
        }
        return Result.ok("修改成功");
    }
}
